<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <title>浏览页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css"/>
</head>
<body class="pear-container">

<!-- 顶部查询表单 -->
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form top-search-from">

            <div class="layui-form-item">
                <label class="layui-form-label">站点名称</label>
                <div class="layui-input-block">
                    <div name="site" id="site" value=""></div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">禁用</label>
                <div class="layui-input-block">
                    <div name="disabled" id="disabled" value=""></div>
                </div>
            </div>

            <div class="layui-form-item layui-inline">
                <label class="layui-form-label"></label>
                <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
                <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                    <i class="layui-icon layui-icon-refresh"></i>重置
                </button>
            </div>
            <div class="toggle-btn">
                <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
            </div>
        </form>
    </div>
</div>

<!-- 数据表格 -->
<div class="layui-card">
    <div class="layui-card-body">
        <table id="data-table" lay-filter="data-table"></table>
    </div>
</div>

<!-- 表格顶部工具栏 -->
<script type="text/html" id="table-toolbar">
    <button class="pear-btn pear-btn-success pear-btn-md" lay-event="backup" permission="admin.site.backup">
        <i class="layui-icon layui-icon-export"></i>全部备份并下载
    </button>
    <button class="pear-btn pear-btn-warming pear-btn-md" id="recovery" permission="admin.site.recovery">
        <i class="layui-icon layui-icon-upload"></i>数据恢复
    </button>
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="bind" permission="admin.site.bind">
        <i class="layui-icon layui-icon-user"></i>绑定合作站点
    </button>
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="test_sid" permission="admin.site.test_sid">
        <i class="layui-icon layui-icon-user"></i>验证站点配置
    </button>
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="sync" permission="admin.site.sync">
        <i class="layui-icon layui-icon-refresh"></i>获取最新站点信息
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="admin.site.delete">
        <i class="layui-icon layui-icon-delete"></i>删除
    </button>
    <button class="pear-btn" id="import" permission="admin.site.import">
        <i class="layui-icon layui-icon-upload"></i>导入旧版配置
    </button>
</script>

<!-- 表格行工具栏 -->
<script type="text/html" id="table-bar">
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="admin.site.update">编辑</button>
</script>

<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script src="/app/admin/admin/js/common.js"></script>

<script>

    // 相关常量
    const PRIMARY_KEY = "id";
    const SELECT_API = "/admin/site/select";
    const UPDATE_API = "/admin/site/update";
    const DELETE_API = "/admin/site/delete";
    const BIND_URL = "/admin/site/bind";
    const TEST_SID_URL = "/admin/site/test_sid";
    const UPDATE_URL = "/admin/site/update";
    const TABLE_COLS_HIDE = 'admin_site_select';

    // 字段 站点名称 site
    layui.use(["jquery", "xmSelect", "popup"], function () {
        layui.$.ajax({
            url: SELECT_API + '?format=select&limit=1000',
            dataType: "json",
            success: function (res) {
                let value = layui.$("#site").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#site",
                    name: "site",
                    initValue: initValue,
                    filterable: true,
                    data: res.data,
                    model: {"icon": "hidden", "label": {"type": "text"}},
                    clickClose: true,
                    radio: true,
                });
                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });
    });

    // 字段 禁用 disabled
    layui.use(["jquery", "xmSelect"], function () {
        let value = layui.$("#disabled").attr("value");
        let initValue = value ? value.split(",") : [];
        layui.xmSelect.render({
            el: "#disabled",
            name: "disabled",
            filterable: true,
            initValue: initValue,
            data: [{"value": "1", "name": "是"}, {"value": "0", "name": "否"}],
            model: {"icon": "hidden", "label": {"type": "text"}},
            clickClose: true,
            radio: true,
        })
    });

    // 表格渲染
    layui.use(["table", "form", "common", "popup", "util", "notice"], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.$;
        let common = layui.common;
        let util = layui.util;

        /**
         * 屏幕宽度小于指定值
         * @param px
         * @returns {boolean}
         */
        function isWidthLessThan(px = 1650) {
            console.info(location.pathname, '屏幕宽度：', layui.$(window).width());
            return layui.$(window).width() <= px;
        }

        // 表头参数
        let cols = [
            {
                type: "checkbox",
                align: "center"
            }, {
                title: "主键", align: "center",
                field: "id",
                width: 80,
            }, {
                title: "站点ID", align: "center",
                field: "sid",
                sort: true,
                width: 80,
            }, {
                title: "站点名称", align: "center",
                field: "site",
                sort: true,
                width: 120,
                templet: function (d) {
                    let field = "site";
                    if (typeof d[field] == "undefined") return "";
                    let items = [];
                    layui.each((d[field] + "").split(","), function (k, v) {
                        items.push(apiResults[field][v] || v);
                    });
                    return util.escape(items.join(","));
                }
            }, {
                title: "昵称", align: "center",
                field: "nickname",
                width: 120,
            }, {
                title: "域名", align: "center",
                field: "base_url",
                hide: true,
            }, {
                title: "镜像域名", align: "center",
                field: "mirror",
                hide: true,
            }, {
                title: "cookie", align: "center",
                field: "cookie",
                width: 60,
                templet: function (d) {
                    let field = "cookie";
                    if (typeof d[field] == "undefined") return "";
                    return d[field] ? 'Yes' : '';
                }
            }, {
                title: "下载种子页", align: "center",
                field: "download_page",
                hide: isWidthLessThan(),
            }, {
                title: "详情页", align: "center",
                field: "details_page",
                hide: isWidthLessThan(),
            }, {
                title: "用户配置值", align: "center",
                field: "options",
                templet: function (d) {
                    return d.options ? JSON.stringify(d.options) : '';
                },
            }, {
                title: "禁用", align: "center",
                field: "disabled",
                width: 100,
                sort: true,
                templet: function (d) {
                    let field = "disabled";
                    form.on("switch(" + field + ")", function (data) {
                        let load = layer.load();
                        let postData = {};
                        postData[field] = data.elem.checked ? 0 : 1;
                        postData[PRIMARY_KEY] = this.value;
                        $.post(UPDATE_API, postData, function (res) {
                            layer.close(load);
                            if (res.code) {
                                return layui.popup.failure(res.msg, function () {
                                    data.elem.checked = !data.elem.checked;
                                    form.render();
                                });
                            }
                            return layui.popup.success(data.elem.checked ? '启用成功' : "已禁用");
                        })
                    });
                    let checked = d[field] === 0 ? "checked" : "";
                    return '<input type="checkbox" title="已启用|已禁用" value="' + util.escape(d[PRIMARY_KEY]) + '" lay-filter="' + util.escape(field) + '" lay-skin="switch" lay-text="' + util.escape('') + '" ' + checked + '/>';
                }
            }, {
                title: "创建时间", align: "center",
                field: "created_at",
                width: 140,
                sort: true,
            }, {
                title: "更新时间", align: "center",
                field: "updated_at",
                width: 140,
                sort: true,
                hide: isWidthLessThan(),
            }, {
                title: "操作",
                toolbar: "#table-bar",
                align: "center",
                fixed: "right",
                width: 70,
            }
        ];

        // 初始化筛选状态
        let local = layui.data(TABLE_COLS_HIDE); // 获取对应的本地记录
        layui.each(cols, function(index, item){
            if(item.field in local){
                item.hide = local[item.field];
            }
        });

        // 渲染表格
        function render() {
            table.render({
                elem: "#data-table",
                url: SELECT_API,
                page: true,
                limit: 20,
                limits: [10, 20, 50, 100, 200],
                cols: [cols],
                //skin: "line",
                size: "sm",
                toolbar: "#table-toolbar",
                autoSort: false,
                defaultToolbar: [{
                    title: "刷新",
                    layEvent: "refresh",
                    icon: "layui-icon-refresh",
                }, "filter", "print"],
                done: function () {
                    layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});

                    // 数据恢复
                    layui.upload.render({
                        elem: '#recovery',
                        url: '/admin/site/recovery',
                        accept: 'file',
                        exts: 'json',
                        dataType: 'json',
                        done: function (res) {
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", refreshTable);
                        }
                    });

                    // 导入旧版配置
                    layui.upload.render({
                        elem: '#import',
                        url: '/admin/site/import',
                        accept: 'file',
                        exts: 'json',
                        dataType: 'json',
                        done: function (res) {
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", refreshTable);
                        }
                    });

                    // 记录筛选状态
                    const that = this;
                    that.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function () {
                        let input = $(this).prev()[0];
                        // 此处表名可任意定义
                        layui.data(TABLE_COLS_HIDE, {
                            key: input.name
                            ,value: input.checked
                        })
                    });
                }
            });
        }

        // 获取表格中下拉或树形组件数据
        let apis = [];
        //apis.push(["site", SELECT_API + '?format=select&limit=1000']);
        let apiResults = {};
        apiResults["site"] = [];
        let count = apis.length;
        layui.each(apis, function (k, item) {
            let [field, url] = item;
            $.ajax({
                url: url,
                dateType: "json",
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }

                    function travel(items) {
                        for (let k in items) {
                            let item = items[k];
                            apiResults[field][item.value] = item.name;
                            if (item.children) {
                                travel(item.children);
                            }
                        }
                    }

                    travel(res.data);
                },
                complete: function () {
                    if (--count === 0) {
                        render();
                    }
                }
            });
        });
        if (!count) {
            render();
        }

        // 编辑或删除行事件
        table.on("tool(data-table)", function (obj) {
            if (obj.event === "remove") {
                remove(obj);
            } else if (obj.event === "edit") {
                edit(obj);
            }
        });

        // 表格顶部工具栏事件
        table.on("toolbar(data-table)", function (obj) {
            if (obj.event === "refresh") {
                refreshTable();
            } else if (obj.event === "batchRemove") {
                batchRemove(obj);
            } else if (obj.event === "bind") {
                bind(obj);
            } else if (obj.event === "test_sid") {
                test_sid(obj);
            } else if (obj.event === "backup") {
                window.open('/admin/site/backup')
            } else if (obj.event === "sync") {
                $.ajax({
                    url: '/admin/site/sync',
                    dataType: "json",
                    success: function (res) {
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        layui.notice.success("同步站点成功");
                        refreshTable();
                    }
                });
            }
        });

        // 表格顶部搜索事件
        form.on("submit(table-query)", function (data) {
            table.reload("data-table", {
                page: {
                    curr: 1
                },
                where: data.field
            })
            return false;
        });

        // 表格顶部搜索重置事件
        form.on("submit(table-reset)", function (data) {
            table.reload("data-table", {
                where: []
            })
        });

        //监听行双击事件
        table.on('rowDouble(data-table)', function (obj) {
            //console.log(obj.tr) //得到当前行元素对象
            console.log(obj.data) //得到当前行数据
            //edit(obj);
            //obj.del(); //删除当前行
            //obj.update(fields) //修改当前行数据
        });

        // 字段允许为空
        form.verify({
            phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
            email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
            url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
            number: [/(^$)|^\d+$/, '只能填写数字'],
            date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
            identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
        });

        // 表格排序事件
        table.on("sort(data-table)", function (obj) {
            table.reload("data-table", {
                initSort: obj,
                scrollPos: "fixed",
                where: {
                    field: obj.field,
                    order: obj.type
                }
            });
        });

        /**
         * 合作站点用户UID绑定
         */
        function bind() {
            layer.open({
                type: 2,
                title: "绑定合作站点，激活IYUU_TOKEN",
                shade: 0.1,
                maxmin: true,
                area: [common.isModile() ? "100%" : "500px", common.isModile() ? "100%" : "450px"],
                content: BIND_URL
            });
        }

        /**
         * 测试站点配置
         */
        function test_sid() {
            layer.open({
                type: 2,
                title: "验证站点配置",
                shade: 0.1,
                maxmin: true,
                area: [common.isModile() ? "100%" : "600px", common.isModile() ? "100%" : "450px"],
                content: TEST_SID_URL
            });
        }

        // 表格编辑数据
        let edit = function (obj) {
            let value = obj.data[PRIMARY_KEY];
            layer.open({
                type: 2,
                title: "修改站点 " + obj.data['site'] + (obj.data['nickname'] ? '（' + obj.data['nickname'] + '）' : ''),
                shade: 0.1,
                maxmin: true,
                area: [common.isModile() ? "100%" : "95%", common.isModile() ? "100%" : "95%"],
                content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value + '&site=' + obj.data['site']
            });
        }

        // 删除一行
        let remove = function (obj) {
            return doRemove(obj.data[PRIMARY_KEY]);
        }

        // 删除多行
        let batchRemove = function (obj) {
            let checkIds = common.checkField(obj, PRIMARY_KEY);
            if (checkIds === "") {
                layui.popup.warning("未选中数据");
                return false;
            }
            doRemove(checkIds.split(","));
        }

        // 执行删除
        let doRemove = function (ids) {
            let data = {};
            data[PRIMARY_KEY] = ids;
            layer.confirm("确定删除?", {
                icon: 3,
                title: "提示"
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    data: data,
                    dataType: "json",
                    type: "post",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        return layui.popup.success("操作成功", refreshTable);
                    }
                })
            });
        }

        // 监听键盘按下esc键 关闭 layer.open的页面
        $(document).keyup(function (e) {
            console.log(e.keyCode)
            if (e.keyCode === 27) {
                layer.closeAll();
            }
        });

        // 刷新表格数据
        window.refreshTable = function (param) {
            table.reloadData("data-table", {
                scrollPos: "fixed"
            });
        }
    })

</script>
</body>
</html>
